<template>
  <div>
    <el-card style="" shadow="hover">
      <el-button type="primary" icon="Plus" @click="addBrand">添加品牌</el-button>
      <br />
      <br />
      <el-table :border="true" :data="datatable">
        <el-table-column label="序号" width="180" align="center" type="index" />
        <el-table-column label="品牌名称" prop="tmName" />
        <el-table-column label="品牌Logo" prop="logoUrl">
          <template #="{ row, $index }">
            <!-- <img :src="row.logoUrl" alt="加载失败" /> -->
            <span>{{ row.logoUrl }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌运营" width="500" align="center">
          <template #="{ row, $index }">
            <el-Button icon="Edit" type="primary" size="small" @click="updateBrand(row)">编辑</el-Button>
            <el-Button icon="Delete" type="danger" size="small" @click="deleteBrand(row)">删除</el-Button>
          </template>
        </el-table-column>
      </el-table>
      <br />
      <br />
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="totalSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog v-model="dialogFormVisible" :title="form.id ? '编辑品牌' : '添加品牌'" width="825">
      <el-form :model="form" style="width: 90%" :rules="rules" ref="formref">
        <el-form-item label="品牌名称" label-width="80px" prop="tmName">
          <el-input v-model="form.tmName" placeholder="输入品牌名称..."></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="80px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="comfireUpdate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
//接口
import { reqAddOrUpdateProduct, reqGetPructions, reqDelProduct } from '@/api/product/BrandManage'
import type { Records, Record } from '@/api/product/BrandManage/type'
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus'
import { log } from 'echarts/types/src/util/log.js'
//表单对象
const formref = ref()
//分页
const currentPage = ref(1)
const pageSize = ref(5)
const totalSize = ref(200)
const handleSizeChange = (val: number) => {
  currentPage.value = 1
  GetProctions()
}
const handleCurrentChange = (val: number) => {
  GetProctions()
}
let datatable = ref<Records>([])
const GetProctions = async () => {
  let result = await reqGetPructions(currentPage.value, pageSize.value)
  if (result.code == 200) {
    totalSize.value = result.data.total
    datatable.value = result.data.records
    // console.log(datatable.value)
  }
}
//挂载初始化
onMounted(() => {
  GetProctions()
})
//模态框
let dialogFormVisible = ref(false)
let modelTitle = ref('')
const imageUrl = ref('')
const addBrand = () => {
  form.logoUrl = ''
  form.tmName = ''
  form.id = 0
  formref.value?.clearValidate()
  dialogFormVisible.value = true
}
const updateBrand = (row: Record) => {
  form.logoUrl = row.logoUrl
  form.tmName = row.tmName
  form.id = row.id
  formref.value?.clearValidate()
  dialogFormVisible.value = true
}
const deleteBrand = async (row: Record) => {
  console.log(row)
  ElMessageBox.confirm('确定要删除吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    let result = await reqDelProduct(row.id)
    console.log(result)
    if (result.code == 200) {
      ElMessage.success('删除成功！')
    }
  })
}
const comfireUpdate = async () => {
  // console.log(formref)
  await formref.value.validate()

  let result = await reqAddOrUpdateProduct(form)
  // console.log(result)
  if (result.code == 200) {
    GetProctions()
    ElMessage.success((form.id ? '修改' : '添加') + '品牌成功！')
  } else {
    ElMessage.error((form.id ? '修改' : '添加') + '品牌失败！')
  }
  dialogFormVisible.value = false
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  form.logoUrl = response.data
  formref.value.clearValidate('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
  if (!(rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif')) {
    ElMessage.error('图片类型必须为png|jpg|gif!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小必须小于 2MB!')
    return false
  }
  return true
}
//表单数据
let form = reactive<Record>({
  tmName: '',
  logoUrl: '',
  id: 0,
})

//表单校验
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.length < 2) callBack(new Error('品牌名称不能小于两位！'))
  else callBack()
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  console.log(value)
  if (!value) callBack(new Error('图片不能为空！'))
  else callBack()
}
const rules = {
  tmName: [{ required: true, Trigger: 'blus', validator: validatorTmName }],
  logoUrl: [{ required: true, Trigger: 'blus', validator: validatorLogoUrl }],
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
